package first.endtoend

import first.endtoend.Beneficiary
import first.endtoend.Family
import first.endtoend.Portfolio

/*
this service return Json Object family with all of beneficiaries related to it
 */

class FamilyService
{

    //HTTP Status Codes 400-416 - Client Error Status Codes

    def addressService

    def serviceMethod()
    {

    }
    def portfolioService
    def beneficiaryService
    def categoryService
    def rationCardService

    def toJson(Family aFamily)
    {
        def listResult
        def portfolio


        if (aFamily != null)
        {
            listResult = new ArrayList<Beneficiary>()

            portfolio = aFamily.portfolio
            aFamily.beneficiaries.each {
                listResult.add(beneficiaryService.toJson(it))
            }
            [
                    id             : aFamily.id,
                    name           : aFamily.familyName,
                    telephone      : aFamily.telephone,
                    address        : addressService.toJson(aFamily.address),
                    beneficiaryList: listResult,
                    portfolio      : portfolioService.toJson(portfolio),
                    category       : categoryService.toJson(aFamily.category),
                    rationCard     : rationCardService.toJson(aFamily.rationCard)

            ]

        } else
        {

            println("family null!")
        }
    }

    def Portfolio getPortfolio(Family family, Date startDate, Date endDate)
    {
        def portfolio = family.portfolio
        if (portfolio) return portfolio
        //The portfolio isn't exist so whe create it (only for new family)
        portfolio = new Portfolio(family: family, startDate: startDate, endDate: endDate)
        if (portfolio.save(flush: true))
            return portfolio
        return null

    }

}
